package es.index.logs.parse.apache;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;

import es.index.document.logs.apache.ApacheErrorLog;
import es.index.logs.parse.GetMonthByString;
import es.index.logs.parse.LogsBaseParse;
import es.index.util.EncodingDetect;

/**
 * 错误日志解析
 * 
 * @author zhoujin
 */
public class ApacheErrorLogsParse extends LogsBaseParse {

	private static String _PATH = "warninglevel.config";
	private static String[] _level = null;

	private String[] dates = null;
	private int index = 0;
	private String dateStr = "";

	static void initLevel() {
		_level = new String[] { "EMERG", "ALERT", "WARNING", "CRIT", "ERROR",
				"WARN", "NOTICE", "INFO", "DEBUG", "信息", "严重" };
	}

	public ApacheErrorLogsParse() {
		final String esPath = System.getProperty("es.index.config");
		// System.out.println("告警级别路径:" + esPath);
		final String path = esPath + _PATH;

		File file = new File(path);
		if (!file.exists()) {
			initLevel();
		} else {
			FileInputStream fis = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			try {
				fis = new FileInputStream(file);
				isr = new InputStreamReader(fis, EncodingDetect.getJavaEncode(file
						.getAbsolutePath()));
				br = new BufferedReader(isr);
				String line = br.readLine();
				if (line != null) {
					line = new String(line.substring(line.indexOf("=") + 1));
					_level = line.split(",");
				}
			} catch (FileNotFoundException e) {
				initLevel();
			} catch (IOException e) {
				initLevel();
			} finally {
				try {
					if (br != null)
						br.close();
					if (isr != null)
						isr.close();
					if (fis != null)
						fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void parse(File file, List<Object> list) throws IOException {
		ApacheErrorLog log = null;
		String level = "";
		// int index = -1;
		boolean isRead = false;
		Date date = null;
		while ((_line = _br.readLine()) != null) {
			// System.out.println(_line);
			if (_line.equals(""))
				continue;
			if ((date = checkData(_line)) != null) {
				isRead = false;
				log = new ApacheErrorLog();
				list.add(log);
				// log.set_id((++index) + "");
				log.set_id(ID());
				log.set_fileName(_fileName);
				log.set_date(date);
				_index = _line.lastIndexOf(" ");
				log.set_class(new String(_line.substring(0, _index).trim()));
				_line = new String(_line.substring(_index));
				_index = _line.lastIndexOf(" ");
				log.set_action(new String(_line.substring(_index).trim()));
			} else {
				int index = _line.indexOf(":");
				if (index > -1) {
					level = new String(_line.substring(0, index));
				} else {
					level = "";
				}
				if (check(level)) {
					log.set_errorLevel(level);
					_line = new String(_line.substring(level.length() + 1));
				}
				log.set_errorContext(log.get_errorContext()
						+ (isRead ? "\n" : "") + _line);
				isRead = true;
			}
		}
	}

	private Date checkData(String line) {
		dates = line.split(" ");

		if ((index = dates[0].indexOf(':')) > -1) {
			if (check(new String(dates[0].substring(0, index))))
				return null;
		}

		try {
			if ((M = GetMonthByString.month(dates[0].trim())) == -1) {
				if (dates.length >= 2) {
					dateStr = dates[0] + " " + dates[1];

					dates = dateStr.split("[ |:|-]");
					if (getDateField(dates, new String[] { "y", "M", "d", "h",
							"m", "s" }, false)) {
						_line = new String(_line.substring(dateStr.length()));
						return getDates(M - 1, y, d, h, m, s);
					}
				}
			} else {
				if (dates.length >= 4) {
					dateStr = dates[0] + " " + dates[1] + " " + dates[2] + " "
							+ dates[3] + " " + dates[4];
					_line = new String(_line.substring(dateStr.length()));
					dateStr = dateStr.replaceFirst(",", "");

					dates = dateStr.split("[ |:]");

					if (getDateField(dates, new String[] { "M", "d", "y", "h",
							"m", "s" }, true)) {
						return getDates(M - 1, y, d, h, m, s);
					}
				}
			}
		} catch (NumberFormatException e) {
			// System.out.println("数据转换错误");
		}
		return null;
	}

	private boolean check(String level) {
		level = level.trim().toUpperCase();
		for (String str : _level) {
			if (str.trim().toUpperCase().equals(level))
				return true;
		}
		// if (level.equals("EMERG") || level.equals("ALERT")
		// || level.equals("WARNING") || level.equals("CRIT")
		// || level.equals("ERROR") || level.equals("WARN")
		// || level.equals("NOTICE") || level.equals("INFO")
		// || level.equals("DEBUG") || level.equals("信息")
		// || level.equals("严重")) {
		// return true;
		// }
		return false;
	}
}
